<template>
  <div class="vehicle-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>车辆管理</h2>
      <p>管理配送车辆信息、司机分配、维护记录等</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="车牌号">
          <el-input v-model="searchForm.vehicleNo" placeholder="请输入车牌号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="车辆状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="正常" value="normal" />
            <el-option label="配送中" value="delivering" />
            <el-option label="维修中" value="maintenance" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-select v-model="searchForm.vehicleType" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="小型货车" value="small" />
            <el-option label="中型货车" value="medium" />
            <el-option label="大型货车" value="large" />
            <el-option label="冷藏车" value="refrigerated" />
          </el-select>
        </el-form-item>
        <el-form-item label="司机姓名">
          <el-input v-model="searchForm.driverName" placeholder="请输入司机姓名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleCreate" :icon="Plus">新增车辆</el-button>
        <el-button type="success" @click="handleBatchAssign" :icon="User" :disabled="!selectedRows.length">批量分配司机</el-button>
        <el-button type="warning" @click="handleBatchMaintenance" :icon="Tools" :disabled="!selectedRows.length">批量维护</el-button>
        <el-button type="info" @click="handleRefresh" :icon="Refresh">刷新</el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" fixed="left">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">{{ row.vehicleNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleType" label="车辆类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getVehicleTypeColor(row.vehicleType)" size="small">{{ getVehicleTypeText(row.vehicleType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌型号" width="150" />
        <el-table-column prop="loadCapacity" label="载重(吨)" width="100" />
        <el-table-column prop="status" label="车辆状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="driverName" label="当前司机" width="100" />
        <el-table-column prop="driverPhone" label="司机电话" width="130" />
        <el-table-column prop="mileage" label="里程(万公里)" width="120" />
        <el-table-column prop="fuelConsumption" label="油耗(L/100km)" width="130" />
        <el-table-column prop="lastMaintenanceDate" label="上次保养" width="120" />
        <el-table-column prop="nextMaintenanceDate" label="下次保养" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': isMaintenanceOverdue(row.nextMaintenanceDate) }">
              {{ row.nextMaintenanceDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="insuranceExpiry" label="保险到期" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': isInsuranceExpiring(row.insuranceExpiry) }">
              {{ row.insuranceExpiry }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)" :icon="View">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" :icon="Edit">编辑</el-button>
            <el-dropdown @command="(command) => handleCommand(command, row)" trigger="click">
              <el-button type="info" size="small" :icon="MoreFilled">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="assign" :icon="User">分配司机</el-dropdown-item>
                  <el-dropdown-item command="maintenance" :icon="Tools">维护记录</el-dropdown-item>
                  <el-dropdown-item command="track" :icon="Location">实时位置</el-dropdown-item>
                  <el-dropdown-item command="disable" :icon="Close" v-if="row.status !== 'disabled'">停用车辆</el-dropdown-item>
                  <el-dropdown-item command="enable" :icon="Check" v-if="row.status === 'disabled'">启用车辆</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑车辆对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="70%"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="vehicleNo">
              <el-input v-model="formData.vehicleNo" placeholder="请输入车牌号" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-select v-model="formData.vehicleType" placeholder="请选择车辆类型" style="width: 100%">
                <el-option label="小型货车" value="small" />
                <el-option label="中型货车" value="medium" />
                <el-option label="大型货车" value="large" />
                <el-option label="冷藏车" value="refrigerated" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌型号" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入品牌型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="载重(吨)" prop="loadCapacity">
              <el-input-number v-model="formData.loadCapacity" :min="0" :max="50" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker
                v-model="formData.purchaseDate"
                type="date"
                placeholder="请选择购买日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前里程(万公里)" prop="mileage">
              <el-input-number v-model="formData.mileage" :min="0" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="油耗(L/100km)" prop="fuelConsumption">
              <el-input-number v-model="formData.fuelConsumption" :min="0" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保险到期日期" prop="insuranceExpiry">
              <el-date-picker
                v-model="formData.insuranceExpiry"
                type="date"
                placeholder="请选择保险到期日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上次保养日期" prop="lastMaintenanceDate">
              <el-date-picker
                v-model="formData.lastMaintenanceDate"
                type="date"
                placeholder="请选择上次保养日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次保养日期" prop="nextMaintenanceDate">
              <el-date-picker
                v-model="formData.nextMaintenanceDate"
                type="date"
                placeholder="请选择下次保养日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 车辆详情对话框 -->
    <el-dialog v-model="detailVisible" title="车辆详情" width="90%">
      <div class="detail-container" v-if="currentRow">
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="车牌号">{{ currentRow.vehicleNo }}</el-descriptions-item>
              <el-descriptions-item label="车辆类型">
                <el-tag :type="getVehicleTypeColor(currentRow.vehicleType)" size="small">{{ getVehicleTypeText(currentRow.vehicleType) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="车辆状态">
                <el-tag :type="getStatusType(currentRow.status)">{{ getStatusText(currentRow.status) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="品牌型号">{{ currentRow.brand }}</el-descriptions-item>
              <el-descriptions-item label="载重">{{ currentRow.loadCapacity }}吨</el-descriptions-item>
              <el-descriptions-item label="购买日期">{{ currentRow.purchaseDate }}</el-descriptions-item>
              <el-descriptions-item label="当前里程">{{ currentRow.mileage }}万公里</el-descriptions-item>
              <el-descriptions-item label="油耗">{{ currentRow.fuelConsumption }}L/100km</el-descriptions-item>
              <el-descriptions-item label="保险到期">{{ currentRow.insuranceExpiry }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <!-- 司机信息 -->
          <el-tab-pane label="司机信息" name="driver">
            <el-descriptions :column="2" border v-if="currentRow.driverName">
              <el-descriptions-item label="司机姓名">{{ currentRow.driverName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ currentRow.driverPhone }}</el-descriptions-item>
              <el-descriptions-item label="驾驶证号">{{ currentRow.driverLicense || '未录入' }}</el-descriptions-item>
              <el-descriptions-item label="从业资格证">{{ currentRow.qualificationCert || '未录入' }}</el-descriptions-item>
              <el-descriptions-item label="分配日期">{{ currentRow.assignDate || '未录入' }}</el-descriptions-item>
              <el-descriptions-item label="驾驶经验">{{ currentRow.drivingExperience || '未录入' }}年</el-descriptions-item>
            </el-descriptions>
            <el-empty v-else description="暂未分配司机" />
          </el-tab-pane>

          <!-- 维护记录 -->
          <el-tab-pane label="维护记录" name="maintenance">
            <el-table :data="currentRow.maintenanceRecords" border>
              <el-table-column prop="date" label="维护日期" width="120" />
              <el-table-column prop="type" label="维护类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.type === 'routine' ? 'success' : 'warning'" size="small">
                    {{ row.type === 'routine' ? '常规保养' : '故障维修' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="维护内容" show-overflow-tooltip />
              <el-table-column prop="cost" label="费用(元)" width="100" />
              <el-table-column prop="mileage" label="维护时里程" width="120" />
              <el-table-column prop="nextMaintenance" label="下次保养里程" width="140" />
            </el-table>
          </el-tab-pane>

          <!-- 配送记录 -->
          <el-tab-pane label="配送记录" name="delivery">
            <el-table :data="currentRow.deliveryRecords" border>
              <el-table-column prop="date" label="配送日期" width="120" />
              <el-table-column prop="orderNo" label="配货单号" width="140" />
              <el-table-column prop="customer" label="客户" width="150" />
              <el-table-column prop="distance" label="配送距离(km)" width="120" />
              <el-table-column prop="fuelCost" label="油费(元)" width="100" />
              <el-table-column prop="status" label="配送状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'completed' ? 'success' : 'warning'" size="small">
                    {{ row.status === 'completed' ? '已完成' : '进行中' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 司机分配对话框 -->
    <el-dialog v-model="assignVisible" title="分配司机" width="50%">
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="选择司机">
          <el-select v-model="assignForm.driverId" placeholder="请选择司机" style="width: 100%">
            <el-option
              v-for="driver in availableDrivers"
              :key="driver.id"
              :label="`${driver.name} - ${driver.phone}`"
              :value="driver.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配日期">
          <el-date-picker
            v-model="assignForm.assignDate"
            type="date"
            placeholder="请选择分配日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="assignForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  View,
  Delete,
  User,
  Tools,
  MoreFilled,
  Location,
  Close,
  Check
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const assignVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')
const currentRow = ref(null)
const selectedRows = ref([])
const formRef = ref(null)
const activeTab = ref('basic')

// 搜索表单
const searchForm = reactive({
  vehicleNo: '',
  status: '',
  vehicleType: '',
  driverName: ''
})

// 表单数据
const formData = reactive({
  vehicleNo: '',
  vehicleType: '',
  brand: '',
  loadCapacity: 0,
  purchaseDate: '',
  mileage: 0,
  fuelConsumption: 0,
  insuranceExpiry: '',
  lastMaintenanceDate: '',
  nextMaintenanceDate: '',
  remark: ''
})

// 司机分配表单
const assignForm = reactive({
  driverId: '',
  assignDate: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  vehicleNo: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
  vehicleType: [{ required: true, message: '请选择车辆类型', trigger: 'change' }],
  brand: [{ required: true, message: '请输入品牌型号', trigger: 'blur' }],
  loadCapacity: [{ required: true, message: '请输入载重', trigger: 'blur' }],
  purchaseDate: [{ required: true, message: '请选择购买日期', trigger: 'change' }]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 可用司机列表
const availableDrivers = ref([
  { id: 1, name: '张师傅', phone: '13800138001', license: '110101199001011234', experience: 8 },
  { id: 2, name: '李师傅', phone: '13800138002', license: '110101199002022345', experience: 12 },
  { id: 3, name: '王师傅', phone: '13800138003', license: '110101199003033456', experience: 6 },
  { id: 4, name: '赵师傅', phone: '13800138004', license: '110101199004044567', experience: 10 }
])

// 模拟数据
const mockData = [
  {
    id: 1,
    vehicleNo: '京A12345',
    vehicleType: 'medium',
    brand: '东风天锦',
    loadCapacity: 8.0,
    status: 'delivering',
    driverName: '张师傅',
    driverPhone: '13800138001',
    driverLicense: '110101199001011234',
    qualificationCert: 'JX001234567',
    assignDate: '2024-01-01',
    drivingExperience: 8,
    mileage: 15.2,
    fuelConsumption: 12.5,
    purchaseDate: '2020-03-15',
    lastMaintenanceDate: '2024-01-10',
    nextMaintenanceDate: '2024-04-10',
    insuranceExpiry: '2024-12-31',
    maintenanceRecords: [
      { date: '2024-01-10', type: 'routine', description: '更换机油、机滤、空滤', cost: 800, mileage: 15.0, nextMaintenance: 18.0 },
      { date: '2023-10-15', type: 'repair', description: '更换刹车片', cost: 1200, mileage: 14.2, nextMaintenance: 15.0 }
    ],
    deliveryRecords: [
      { date: '2024-01-14', orderNo: 'PH202401001', customer: '华润万家', distance: 25, fuelCost: 45, status: 'completed' },
      { date: '2024-01-15', orderNo: 'PH202401005', customer: '沃尔玛', distance: 18, fuelCost: 32, status: 'delivering' }
    ]
  },
  {
    id: 2,
    vehicleNo: '京B67890',
    vehicleType: 'small',
    brand: '福田祥菱',
    loadCapacity: 3.5,
    status: 'normal',
    driverName: '李师傅',
    driverPhone: '13800138002',
    driverLicense: '110101199002022345',
    qualificationCert: 'JX001234568',
    assignDate: '2024-01-02',
    drivingExperience: 12,
    mileage: 8.7,
    fuelConsumption: 9.8,
    purchaseDate: '2021-06-20',
    lastMaintenanceDate: '2024-01-05',
    nextMaintenanceDate: '2024-04-05',
    insuranceExpiry: '2024-11-30',
    maintenanceRecords: [
      { date: '2024-01-05', type: 'routine', description: '常规保养', cost: 600, mileage: 8.5, nextMaintenance: 11.5 }
    ],
    deliveryRecords: [
      { date: '2024-01-13', orderNo: 'PH202401002', customer: '家乐福', distance: 12, fuelCost: 22, status: 'completed' }
    ]
  },
  {
    id: 3,
    vehicleNo: '京C11111',
    vehicleType: 'large',
    brand: '解放J6',
    loadCapacity: 15.0,
    status: 'maintenance',
    driverName: '王师傅',
    driverPhone: '13800138003',
    driverLicense: '110101199003033456',
    qualificationCert: 'JX001234569',
    assignDate: '2024-01-03',
    drivingExperience: 6,
    mileage: 22.5,
    fuelConsumption: 18.2,
    purchaseDate: '2019-08-10',
    lastMaintenanceDate: '2024-01-12',
    nextMaintenanceDate: '2024-01-20',
    insuranceExpiry: '2024-08-31',
    maintenanceRecords: [
      { date: '2024-01-12', type: 'repair', description: '发动机大修', cost: 8000, mileage: 22.5, nextMaintenance: 25.0 }
    ],
    deliveryRecords: [
      { date: '2024-01-10', orderNo: 'PH202401003', customer: '大润发', distance: 45, fuelCost: 95, status: 'completed' }
    ]
  },
  {
    id: 4,
    vehicleNo: '京D22222',
    vehicleType: 'refrigerated',
    brand: '欧曼冷藏车',
    loadCapacity: 10.0,
    status: 'normal',
    driverName: '赵师傅',
    driverPhone: '13800138004',
    driverLicense: '110101199004044567',
    qualificationCert: 'JX001234570',
    assignDate: '2024-01-04',
    drivingExperience: 10,
    mileage: 12.8,
    fuelConsumption: 15.5,
    purchaseDate: '2020-12-01',
    lastMaintenanceDate: '2024-01-08',
    nextMaintenanceDate: '2024-04-08',
    insuranceExpiry: '2024-12-01',
    maintenanceRecords: [
      { date: '2024-01-08', type: 'routine', description: '冷藏设备检修', cost: 1500, mileage: 12.5, nextMaintenance: 15.5 }
    ],
    deliveryRecords: [
      { date: '2024-01-11', orderNo: 'PH202401004', customer: '盒马鲜生', distance: 28, fuelCost: 58, status: 'completed' }
    ]
  },
  {
    id: 5,
    vehicleNo: '京E33333',
    vehicleType: 'medium',
    brand: '江淮骏铃',
    loadCapacity: 6.0,
    status: 'disabled',
    driverName: '',
    driverPhone: '',
    mileage: 25.6,
    fuelConsumption: 13.8,
    purchaseDate: '2018-05-15',
    lastMaintenanceDate: '2023-12-20',
    nextMaintenanceDate: '2024-03-20',
    insuranceExpiry: '2024-05-15',
    maintenanceRecords: [
      { date: '2023-12-20', type: 'repair', description: '变速箱维修', cost: 5000, mileage: 25.6, nextMaintenance: 28.0 }
    ],
    deliveryRecords: []
  }
]

// 获取车辆类型颜色
const getVehicleTypeColor = (type) => {
  const colorMap = {
    small: 'success',
    medium: 'warning',
    large: 'danger',
    refrigerated: 'primary'
  }
  return colorMap[type] || 'info'
}

// 获取车辆类型文本
const getVehicleTypeText = (type) => {
  const textMap = {
    small: '小型货车',
    medium: '中型货车',
    large: '大型货车',
    refrigerated: '冷藏车'
  }
  return textMap[type] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    normal: 'success',
    delivering: 'primary',
    maintenance: 'warning',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    normal: '正常',
    delivering: '配送中',
    maintenance: '维修中',
    disabled: '停用'
  }
  return statusMap[status] || '未知'
}

// 检查保养是否过期
const isMaintenanceOverdue = (date) => {
  if (!date) return false
  const today = new Date()
  const maintenanceDate = new Date(date)
  return maintenanceDate < today
}

// 检查保险是否即将到期
const isInsuranceExpiring = (date) => {
  if (!date) return false
  const today = new Date()
  const expiryDate = new Date(date)
  const diffTime = expiryDate - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays <= 30 && diffDays >= 0
}

// 加载数据
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    vehicleNo: '',
    status: '',
    vehicleType: '',
    driverName: ''
  })
  loadData()
}

// 刷新
const handleRefresh = () => {
  loadData()
}

// 新建
const handleCreate = () => {
  isEdit.value = false
  dialogTitle.value = '新增车辆'
  Object.assign(formData, {
    vehicleNo: '',
    vehicleType: '',
    brand: '',
    loadCapacity: 0,
    purchaseDate: '',
    mileage: 0,
    fuelConsumption: 0,
    insuranceExpiry: '',
    lastMaintenanceDate: '',
    nextMaintenanceDate: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑车辆'
  Object.assign(formData, {
    vehicleNo: row.vehicleNo,
    vehicleType: row.vehicleType,
    brand: row.brand,
    loadCapacity: row.loadCapacity,
    purchaseDate: row.purchaseDate,
    mileage: row.mileage,
    fuelConsumption: row.fuelConsumption,
    insuranceExpiry: row.insuranceExpiry,
    lastMaintenanceDate: row.lastMaintenanceDate,
    nextMaintenanceDate: row.nextMaintenanceDate,
    remark: row.remark || ''
  })
  currentRow.value = row
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  currentRow.value = row
  activeTab.value = 'basic'
  detailVisible.value = true
}

// 命令处理
const handleCommand = (command, row) => {
  switch (command) {
    case 'assign':
      currentRow.value = row
      Object.assign(assignForm, {
        driverId: '',
        assignDate: new Date().toISOString().split('T')[0],
        remark: ''
      })
      assignVisible.value = true
      break
    case 'maintenance':
      ElMessage.info('维护记录功能开发中...')
      break
    case 'track':
      ElMessage.info('实时位置跟踪功能开发中...')
      break
    case 'disable':
      ElMessageBox.confirm('确定要停用此车辆吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success('车辆已停用')
        loadData()
      })
      break
    case 'enable':
      ElMessageBox.confirm('确定要启用此车辆吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success('车辆已启用')
        loadData()
      })
      break
  }
}

// 批量分配司机
const handleBatchAssign = () => {
  ElMessage.info('批量分配司机功能开发中...')
}

// 批量维护
const handleBatchMaintenance = () => {
  ElMessage.info('批量维护功能开发中...')
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '车辆信息更新成功' : '车辆添加成功')
        submitLoading.value = false
        dialogVisible.value = false
        loadData()
      }, 1000)
    }
  })
}

// 司机分配提交
const handleAssignSubmit = () => {
  if (!assignForm.driverId) {
    ElMessage.warning('请选择司机')
    return
  }
  ElMessage.success('司机分配成功')
  assignVisible.value = false
  loadData()
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.vehicle-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-container {
  padding: 20px 0;
}

.text-danger {
  color: #f56c6c;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .vehicle-management-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>